#!/bin/bash

if [ `whoami` != 'root' ]; then
	echo "Please run this program as root (type: sudo $0)"
	exit 1
fi

echo Installing Context Firewall server and client components...
# ----------------------------------------------------------------
# Apply kernel patch

echo Applying kernel patch...
cd binary/kernel
./fixmodules
if [ $? -ne "0" ]; then
    cd ../..
    echo "Failed applying kernel patch. Please correct the errors"
    exit 1
fi
cd ../..

echo Done applying kernel patch
# ----------------------------------------------------------------

# ----------------------------------------------------------------
# Compile the code

echo Compiling code...
./compile_server_side
if [ $? -ne "0" ]; then
    echo "Failed compiling code. Please correct the errors"
    exit 1
fi

echo Done compiling code
# ----------------------------------------------------------------

# ----------------------------------------------------------------
# Copy .so file

echo Copying shared object...
cd binary
cp libipt_ipcontext.so /lib/iptables
if [ $? -ne "0" ]; then
    cd ..
    echo "Failed copying shared object. Please correct the errors"
    exit 1
fi
cd ..

echo Done copying shared object
# ----------------------------------------------------------------

# ----------------------------------------------------------------
# Initialize the DB

echo Initializing DB...
cd binary
./initdb
if [ $? -ne "0" ]; then
    cd ..
    echo "Failed initializing DB. Please correct the errors"
    exit 1
fi
cd ..

echo Done initializing DB
# ----------------------------------------------------------------

# ----------------------------------------------------------------
# Building and adding Server's boot script

echo "Boot script..."
cd binary
./initboot
if [ $? -ne "0" ]; then
    cd ..
    echo "Failed initializing boot script. Please correct the errors"
    exit 1
fi
cd ..

echo "Done initializing boot env."
# ----------------------------------------------------------------


echo All done - Context Firewall ready for use
